package com.example.administrator.myapplication;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.widget.Toolbar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MerchandiseControlActivity extends AppCompatActivity{
    private ListView mListView;
    private Button mButton;
    private Handler mHandler,mHandler2;
    private Context mContext;
    private MerchandiseAdapter adapter;
    private RelativeLayout relativeLayout;
    private Toolbar toolbar;
    private TextView boxTextView1, boxTextView2, boxTextView3;
    private SwipeRefreshLayout refreshLayout;
    private LinearLayout linearLayout;
    private View footView,headView;
    private ImageView boxPicture1, boxPicture2, boxPicture3;
    private BoxAdapter adapter1;
    private ArrayList<BoxList> item1 = new ArrayList<>();
    private  ArrayList<SkuList> item = new ArrayList<>();
    private ArrayList<BoxPowerList> item2=new ArrayList<>();
    public MerchandiseControlActivity() {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchandisecontrol);
        adapter = new MerchandiseAdapter(MerchandiseControlActivity.this);
        adapter1 = new BoxAdapter(MerchandiseControlActivity.this);
        initView();
        setRefreshLayout();
        initToolBar();
        getAccessToken();
        httpContect();
        handlerGetData();
        mHandler1GetData();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(MerchandiseControlActivity.this, AddMerchandiseActivity.class);
                startActivity(mIntent);
            }
        });
        itemMemberResolve();

    }

    /*
     *
     * TODO:加载ToolBar
     *
     * */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initToolBar() {
        toolbar.inflateMenu(R.menu.menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_compose:
                        Intent mIntent = new Intent(MerchandiseControlActivity.this, AddMerchandiseActivity.class);
                        startActivity(mIntent);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

    }

    /*
     * TODO:处理listview的headview
     * */
    private void headViewResolve() {
        LayoutInflater layoutInflater = LayoutInflater.from(MerchandiseControlActivity.this);
         headView = layoutInflater.inflate(R.layout.headview, null);
        if (mListView.getHeaderViewsCount() == 0) {
            mListView.addHeaderView(headView);
        }
    }
    /*
    *
    * TODO:绑定listview
    *
    * */
    private void bindingListview(final int Boxid){
        ListView mListview1=new ListView(MerchandiseControlActivity.this);
        ScrollView mScrollView=new ScrollView(MerchandiseControlActivity.this);
        LinearLayout linearLayout=new LinearLayout(MerchandiseControlActivity.this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
        mListview1.setAdapter(adapter1);
        Button mButton=new Button(MerchandiseControlActivity.this);
        mButton.setText("取消");
        mScrollView.addView(mListview1,params);
        linearLayout.addView(mScrollView,params);
        linearLayout.addView(mButton,params);
        final Dialog dialog=new Dialog(this,R.style.ActionSheetDialogStyle);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        mListview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        HttpContect httpContect=new HttpContect();
                                        String route="api/goods/update-box";
                                        String access_token=getAccessToken();
                                        int  skuId=item2.get(position).sku_id;
                                        String data="access_token="+access_token+"&sku_id="+skuId+"&box_num="+Boxid;
                                        httpContect.send(route,data);
                                        httpContect();
                                    }
                                }).start();
                    dialog.dismiss();
            }
        });
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.setTitle("请选择添加的豆粉");
        dialog.setContentView(linearLayout);
        dialog.show();


    }
    /*
     * TODO:处理listview的footview
     *
     * */
    private void footViewResolve() {

        LayoutInflater layoutInflater = LayoutInflater.from(MerchandiseControlActivity.this);
        footView = layoutInflater.inflate(R.layout.footer, null);
        boxTextView1 = footView.findViewById(R.id.tv1);
        boxTextView2 = footView.findViewById(R.id.tv2);
        boxTextView3 = footView.findViewById(R.id.tv3);
        boxPicture1 = footView.findViewById(R.id.iv1);
        boxPicture2 = footView.findViewById(R.id.iv2);
        boxPicture3 = footView.findViewById(R.id.iv3);
        if (item1.get(0).status == 0) {
            boxPicture1.setBackgroundResource(R.mipmap.ic_launcher);
        } else if (item1.get(0).status == 1) {
            boxPicture1.setBackgroundResource(R.drawable.ic_launcher_background);
        }

        if (item1.get(1).status == 0) {
            boxPicture2.setBackgroundResource(R.mipmap.ic_launcher);
        } else if (item1.get(1).status == 1) {
            boxPicture2.setBackgroundResource(R.drawable.ic_launcher_background);
        }
        if (item1.get(2).status == 0) {
            boxPicture3.setBackgroundResource(R.mipmap.ic_launcher);
        } else if (item1.get(2).status == 1) {
            boxPicture3.setBackgroundResource(R.drawable.ic_launcher_background);
        }
        boxTextView1.setText(item1.get(0).getName());
        boxTextView2.setText(item1.get(1).getName());
        boxTextView3.setText(item1.get(2).getName());
        boxTextView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int boxid=1;
                bindingListview(boxid);
                boxList(boxid);
            }
        });
        boxTextView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int boxid=2;
                bindingListview(boxid);
                boxList(boxid);
            }
        });
        boxTextView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int boxid=3;
                bindingListview(boxid);

                boxList(boxid);
            }
        });
    }
    /*

    TODO：粉盒列表

    */

    private void boxList(final int boxId){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpContect httpContect=new HttpContect();
                        String route="api/goods/box-goods-list";
                        String access_token=getAccessToken();
                        String data="access_token="+access_token+"&box_id="+boxId;
                       String JSONData =httpContect.send(route,data);
                        Message message=new Message();
                        message.obj=JSONData;
                        mHandler2.sendMessage(message);
                    }
                }).start();
    }

    /*
     * TODO:网络请求
     *
     * */
    private void httpContect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpContect httpContect = new HttpContect();
                String route = "api/goods/sku-list";
                String data = "access_token=" + getAccessToken();
                String getReturnJsonData = httpContect.send(route, data);
                Looper.prepare();
                Message message = new Message();
                message.obj = getReturnJsonData;
                mHandler.sendMessage(message);
                Looper.loop();
            }
        }).start();
    }

    /*
     * TODO:刷新页面
     *
     * */
    private void setRefreshLayout() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (refreshLayout.isRefreshing()) {
                    httpContect();
                    refreshLayout.setRefreshing(false);
                }
            }
        });
    }
    /*
     * TODO:Handler2传输数据
     * */
    private void mHandler1GetData(){
        mHandler2=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String JsonVale= (String) msg.obj;
            JsonBoxReslveData(JsonVale);
            super.handleMessage(msg);
        }
    };

}
/*
* TODO:解析数据
*
* */
    public void JsonBoxReslveData(String JsonVale){
        try {
            JSONObject jsonObject=new JSONObject(JsonVale);
            JSONObject data=jsonObject.getJSONObject("data");
            JSONArray sku_list=data.getJSONArray("sku_list");
            item2.clear();
            for (int i=0;i<sku_list.length();i++){
                BoxPowerList mList=new BoxPowerList();
                JSONObject jsonObject1= (JSONObject) sku_list.get(i);
                int sku_id=jsonObject1.optInt("sku_id");
                String sku_name=jsonObject1.optString("sku_name");
                mList.setSku_name(sku_name);
                mList.setSku_id(sku_id);
                item2.add(mList);
            }
            adapter1.setData(item2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    /*
     *
     * TODO:list view item中的控件
     * */
  public void itemMemberResolve(){
      adapter.setListener(new MerchandiseAdapter.onMyAdapterClicklistener() {
          @Override
          public void onDeleteClick(final int position) {
              AlertDialog.Builder builder=new AlertDialog.Builder(MerchandiseControlActivity.this);
              builder.setMessage("是否删除"+adapter.data.get(position).sku_name);
              builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      new Thread(new Runnable() {
                          @Override
                          public void run() {
                              HttpContect httpContect=new HttpContect();
                              String route="api/goods/del-sku";
                              String access_token=getAccessToken();
                              int sku_id=adapter.data.get(position).sku_id;
                              String data="access_token="+access_token+"&sku_id="+sku_id;
                              httpContect.send(route,data);
                          }
                      }).start();
                    httpContect();
                  }
              });
              builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    httpContect();
                  }
              });
              AlertDialog dialog=builder.create();
              dialog.show();
          }

          @Override
          public void onReviseClick(int position) {
              Intent mIntent=new Intent(MerchandiseControlActivity.this,ReviseMerchandiseActivity.class);
              String  sku_id= String.valueOf(adapter.data.get(position).sku_id);
              String  price= String.valueOf(adapter.data.get(position).price);
              mIntent.putExtra("sku_id",sku_id);
              mIntent.putExtra("price",price);
              String  sku_name= String.valueOf(adapter.data.get(position).sku_name);
              mIntent.putExtra("sku_name",sku_name);
              startActivity(mIntent);
          }

          @Override
          public void onSwitchClick(final int position, final boolean isChecked) {
              if (isChecked){
                  AlertDialog.Builder builder=new AlertDialog.Builder(MerchandiseControlActivity.this);
                  builder.setMessage("是否上架"+adapter.data.get(position).sku_name);
                  builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpContect httpContect=new HttpContect();
                                String route="api/goods/sale-status";
                                int onSale=1;
                                String accessToken=getAccessToken();
                                int  skuId=adapter.data.get(position).sku_id;
                                String data="access_token="+accessToken+"&sku_id="+skuId+"&on_sale="+onSale;
                                httpContect.send(route,data);
                                httpContect();
                            }
                        }).start();


                      }
                  });
                  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                            httpContect();
                      }
                  });
                  AlertDialog dialog=builder.create();
                  dialog.show();
              }else if (!isChecked){
                  AlertDialog.Builder builder=new AlertDialog.Builder(MerchandiseControlActivity.this);
                  builder.setMessage("是否下架"+adapter.data.get(position).sku_name);
                  builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          new Thread(new Runnable() {
                              @Override
                              public void run() {
                                  HttpContect httpContect=new HttpContect();
                                  String route="api/goods/sale-status";
                                  int onSale=0;
                                  String accessToken=getAccessToken();
                                  int  skuId=adapter.data.get(position).sku_id;
                                  String data="access_token="+accessToken+"&sku_id="+skuId+"&on_sale="+onSale;
                                  httpContect.send(route,data);
                                  httpContect();
                              }
                          }).start();
                      }
                  });
                  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          httpContect();
                      }
                  });
                  AlertDialog dialog=builder.create();
                  dialog.show();
              }


          }
      });

  }

    /*
     * TODO：获取token
     *
     * */

    private String getAccessToken() {
        SharedPreferences sharedPreferences = getSharedPreferences("data", 0);
        sharedPreferences.getString("access_token", null);
        String access_token = sharedPreferences.getString("access_token", null);
        return access_token;
    }
    /*
     * TODO:Handler传输数据
     * */

    private void handlerGetData() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String jsonGetData = (String) msg.obj;
                resolveJsonData(jsonGetData);
                super.handleMessage(msg);
            }
        };
    }

    /*
     * TODO:解析JSON的数据
     * */
    private void resolveJsonData(String jsonData) {
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray sku_list = data.getJSONArray("sku_list");
            JSONObject box = data.getJSONObject("box");
            JSONArray box_data = box.getJSONArray("box_data");
            item1.clear();
            for (int i = 0; i <box_data.length(); i++) {
                BoxList lists = new BoxList();
                JSONObject box_data_value = (JSONObject) box_data.get(i);
                int box_id = box_data_value.optInt("id");
                String name = box_data_value.optString("name");
                int status = box_data_value.optInt("status");
                lists.setId(box_id);
                lists.setName(name);
                lists.setStatus(status);
                item1.add(lists);
            }

            int show_status = box.optInt("show_status");
            mListView.removeFooterView(footView);

            if (show_status == 1) {

                footViewResolve();
                mListView.addFooterView(footView);
            }
            if (sku_list.length() > 0) {
                relativeLayout.setVisibility(View.GONE);
                headViewResolve();

            }
            item.clear();
            for (int i = 0; i <= sku_list.length() - 1; i++) {
                JSONObject sku_list_data = (JSONObject) sku_list.get(i);
                SkuList list = new SkuList();
                int id = sku_list_data.optInt("id");
                int sku_id = sku_list_data.optInt("sku_id");
                String sku_name = sku_list_data.optString("sku_name");
                int on_sale = sku_list_data.optInt("on_sale");
                Double price = sku_list_data.optDouble("price");
                String cup_type = sku_list_data.optString("cup_type");
                list.setId(id);
                list.setSku_name(sku_name);
                list.setSku_id(sku_id);
                list.setOn_sale(on_sale);
                list.setCup_type(cup_type);
                list.setPrice(price);
                item.add(list);
            }
            adapter.setData(item);
            mListView.setAdapter(adapter);
            adapter.notifyDataSetChanged();


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }/*

    TODO:关联粉盒关系

    */


    /*
     * TODO:初始化控件
     *
     * */
    private void initView() {
        mListView = findViewById(R.id.merchandiselistview);
        mButton = findViewById(R.id.addmerchandise_button);
        relativeLayout = findViewById(R.id.empty_merchandise);
        toolbar = findViewById(R.id.toolbar);
        refreshLayout = findViewById(R.id.fl1);
    }

}

